#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
PyQt6主窗口
统一管理所有功能页面
"""

import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QTabWidget, 
                            QVBoxLayout, QWidget, QStatusBar, QLabel)

from gui.pages.pyqt6_socket_server_page import SocketServerPage
from gui.pages.pyqt6_socket_client_page import SocketClientPage
from gui.pages.pyqt6_modbus_collection_page import ModbusCollectionPage
from gui.pages.pyqt6_modbus_simulator_page import ModbusSimulatorPage


class MainWindow(QMainWindow):
    """PyQt6主窗口类"""
    
    def __init__(self):
        """初始化主窗口"""
        super().__init__()
        self.setWindowTitle("IoT工具集 - 统一调试平台 (PyQt6版)")
        self.setGeometry(100, 100, 1400, 900)
        
        # 页面管理
        self.pages = {}
        self.current_page = None
        
        # 初始化界面
        self._init_ui()
        
    def _init_ui(self):
        """初始化UI界面"""
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(5, 5, 5, 5)
        main_layout.setSpacing(5)
        
        # 创建标签页控件
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabsClosable(False)
        self.tab_widget.tabBar().setDocumentMode(True)
        self.tab_widget.tabBar().setExpanding(True)
        
        # 绑定标签页切换事件
        self.tab_widget.currentChanged.connect(self._on_tab_changed)
        
        main_layout.addWidget(self.tab_widget)
        
        # 创建各个页面
        self._create_pages()
        
        # 创建状态栏
        self._create_status_bar()
        
    def _create_pages(self):
        """创建所有功能页面"""
        # 1. Socket服务器页面
        socket_server_page = SocketServerPage()
        self.tab_widget.addTab(socket_server_page, "Socket服务器")
        self.pages["socket_server"] = socket_server_page

        # 2. Socket客户端页面
        socket_client_page = SocketClientPage()
        self.tab_widget.addTab(socket_client_page, "Socket客户端")
        self.pages["socket_client"] = socket_client_page

        # 3. Modbus采集调试页面
        modbus_collection_page = ModbusCollectionPage()
        self.tab_widget.addTab(modbus_collection_page, "Modbus采集调试")
        self.pages["modbus_collection"] = modbus_collection_page

        # 4. Modbus模拟器页面
        modbus_simulator_page = ModbusSimulatorPage()
        self.tab_widget.addTab(modbus_simulator_page, "Modbus模拟器")
        self.pages["modbus_simulator"] = modbus_simulator_page

        # 显示第一个页面
        if self.pages:
            self.current_page = list(self.pages.values())[0]
    
    def _create_status_bar(self):
        """创建状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_bar.addWidget(self.status_label)
        
        # 添加弹簧空间
        self.status_bar.addPermanentWidget(QLabel(" "))
        
        # 版本信息
        version_label = QLabel("版本: v2.0.0")
        self.status_bar.addPermanentWidget(version_label)
        
        # 右侧信息
        info_label = QLabel("IoT工具集 - PyQt6版")
        self.status_bar.addPermanentWidget(info_label)
    
    def _on_tab_changed(self, index):
        """标签页切换事件处理"""
        try:
            page_names = list(self.pages.keys())
            if index < len(page_names):
                page_name = page_names[index]
                new_page = self.pages[page_name]
                self.current_page = new_page
                
                # 更新状态栏
                self.status_label.setText(f"当前页面: {new_page.title}")
                
        except Exception as e:
            print(f"标签页切换错误: {e}")
    
    def closeEvent(self, event):
        """窗口关闭事件处理"""
        try:
            # 关闭所有页面
            for page in self.pages.values():
                try:
                    page.on_close()
                except Exception as e:
                    print(f"关闭页面错误: {e}")
            
            event.accept()
        except Exception as e:
            print(f"关闭程序错误: {e}")
            event.accept()


def main():
    """主函数"""
    try:
        app = QApplication(sys.argv)
        app.setApplicationName("IoT工具集")
        app.setApplicationVersion("2.0.0")
        
        # 创建并显示主窗口
        window = MainWindow()
        window.show()
        
        sys.exit(app.exec())
    
    except Exception as e:
        print(f"程序运行错误: {e}")


if __name__ == "__main__":
    main()